package com.TeacherInfoServer.listener;

import com.TeacherInfoServer.exception.JobNumberRepeatedDetailException;
import com.TeacherInfoServer.exception.RecordExistDetailException;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.pojo.entity.TeacherInfoChange;
import com.TeacherInfoServer.pojo.excelImport.TeacherInfoChangeExcel;
import com.TeacherInfoServer.common.service.CommentService;
import com.TeacherInfoServer.common.service.TeacherInfoChangeService;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TypeInfoService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Data
@Slf4j
@Component
public class TeacherInfoChangeListener implements ReadListener<TeacherInfoChangeExcel> {
    @Autowired
    public TeacherInfoChangeService teacherInfoChangeService;
    @Autowired
    public CommentService commentService;
    @Autowired
    public TypeInfoService typeInfoService;
    @Autowired
    public TeacherService teacherService;
    @Autowired
    private Validator validator;
    private final List<TeacherInfoChange> teacherInfoChangeList = new ArrayList<>();
    private final List<TeacherInfoChange> updateList = new ArrayList<>();
    private final List<TeacherInfoChange> addList = new ArrayList<>();
    private final Set<TeacherInfoChangeExcel> teacherInfoChangeSet = new HashSet<>();
    private Integer record;
    @Override
    public void invoke(TeacherInfoChangeExcel teacherInfoChangeExcel, AnalysisContext analysisContext) {
        Set<ConstraintViolation<TeacherInfoChangeExcel>> violations = validator.validate((teacherInfoChangeExcel));
        if (violations.isEmpty()){
            if(teacherService.getOne(teacherInfoChangeExcel.getTeacherId()).getData()!=null){
                Teacher teacher = commentService.getByTeacherId(teacherInfoChangeExcel.getTeacherId());
                if(teacher!=null&&teacher.getTeacherName().equals(teacherInfoChangeExcel.getTeacherName())){
                    if(!teacherInfoChangeSet.contains(teacherInfoChangeExcel)){
                        TeacherInfoChange teacherInfoChange =new TeacherInfoChange(null,
                                teacherInfoChangeExcel.getTeacherId(),
                                typeInfoService.getOneId("变动类型", teacherInfoChangeExcel.getChangeTypeValue()),
                                teacherInfoChangeExcel.getChangeDate(),
                                teacherInfoChangeExcel.getChangeReason());
                        teacherInfoChangeList.add(teacherInfoChange);
                        teacherInfoChangeSet.add(teacherInfoChangeExcel);
                    }else {
                        throw new RecordExistDetailException("表中存在完全相同记录");
                    }
                }else {
                    throw new JobNumberRepeatedDetailException("教师工号："+teacherInfoChangeExcel.getTeacherId()+"与教师姓名："+teacherInfoChangeExcel.getTeacherName()+"与系统中不匹配");
                }

            }else {
                throw new JobNumberRepeatedDetailException("教师工号："+teacherInfoChangeExcel.getTeacherId()+"不存在");
            }


        }else {
            String errorMessage = violations.iterator().next().getMessage();
            throw new ConstraintViolationException(errorMessage, violations);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<TeacherInfoChange> teacherInfoChanges = teacherInfoChangeService.list();
        teacherInfoChangeList.forEach(teacherInfoChange -> {
            Optional<TeacherInfoChange> teacherInfoChangeOptional = teacherInfoChanges.stream()
                    .peek(dbTeacherInfoChange -> dbTeacherInfoChange.setId(null))
                    .filter(teacherInfoChange::equals)
                    .findFirst();
            teacherInfoChangeOptional.ifPresent(dbTeacherInfoChange -> log.info("记录已存在数据库:{}",dbTeacherInfoChange));
            if(teacherInfoChangeOptional.isEmpty()){
                addList.add(teacherInfoChange);

            }

        });
        List<TeacherInfoChange> mergedList = Stream.concat(updateList.stream(),addList.stream()).collect(Collectors.toList());
        teacherInfoChangeService.saveOrUpdateBatch(mergedList);
        setRecord(mergedList.size());
        initList();
    }
    public void initList(){
        teacherInfoChangeList.clear();
        updateList.clear();
        addList.clear();
        teacherInfoChangeSet.clear();
    }
}
